﻿using MailKit;
using MailKit.Net.Imap;
using MailKit.Search;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace mmkit
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            string x = "should it matter";
            x = x + " ?"; //breakpoint (1)
            MailKit.Net.Pop3.Pop3Client pop = new MailKit.Net.Pop3.Pop3Client();
             ImapClient client = new ImapClient();
            string account = "geyao@zhaiugo.com";
            string passWord = "aaaa1111";

            client.Connect("mail.zhaiugo.com", 993, true);

            client.Authenticate(account, passWord);
         
            var folder = client.GetFolder("INBOX");
            folder.Open(MailKit.FolderAccess.ReadOnly);
            var uidss = folder.Search(SearchQuery.DeliveredAfter(DateTime.Parse("2016-9-1")));

            var ss = folder.Fetch(uidss, MessageSummaryItems.UniqueId | MessageSummaryItems.Full);
            //获取完整邮件
            foreach (var item in uidss)
            {
                MimeMessage message = folder.GetMessage(new UniqueId(item.Id));
                string html = message.HtmlBody;
                Debug.WriteLine("HTML--------"+html);
                string TextBody = message.TextBody;
                Debug.WriteLine("TextBody--------" + TextBody);
            }
        }

        public static void HandleMimeEntity(MimeEntity entity)
        {
            //MimeEntity转化为Multipart实体
            var multipart = entity as Multipart;
            if (multipart != null)
            {
                for (int i = 0; i < multipart.Count; i++)
                    HandleMimeEntity(multipart[i]);
                return;
            }
            var rfc822 = entity as MessagePart;

            if (rfc822 != null)
            {
                var message = rfc822.Message;
                HandleMimeEntity(message.Body);
                return;
            }
            var part = (MimePart)entity;
        }
    }
}
